﻿using Microsoft.AspNetCore.Mvc;
using RedisDemo.Services;
using System.Threading.Tasks;

namespace RedisDemo.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CounterController : ControllerBase
    {
        private readonly CounterService _counterService;
        private readonly IDistributedLockFactory _lockFactory;

        public CounterController(
            CounterService counterService,
            IDistributedLockFactory lockFactory)
        {
            _counterService = counterService;
            _lockFactory = lockFactory;
        }

        [HttpGet]
        public async Task UpdateCounter()
        {
            using (var locker = await _lockFactory.LockAsync("sldflksdfj"))
            {
                if (locker.IsAcquired)
                {
                    _counterService.UpdateCounter("TicketType");
                }
            }
        }

        [HttpGet]
        public async Task<JsonResult> GetCounter()
        {
            var result = await _counterService.GetCounter("TicketType", 5);

            return new JsonResult(result);
        }

        [HttpGet]
        public async Task CleanCounter()
        {
            await _counterService.CleanCounters();
        }
    }
}